<template>
  <div class="app-container">
    <div class="header-bar">
      <el-button
          type="primary"
          icon="ArrowLeft"
          @click="handleBack"
          class="back-btn"
      >
        返回
      </el-button>
      <h2 class="page-title">评论管理</h2>
    </div>

    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <!-- 新增评论按钮 -->
      <el-form-item class="action-button">
        <el-button type="primary" icon="Plus" @click="handleAdd" class="add-btn">
          发表评论
        </el-button>
      </el-form-item>

      <!-- 评论状态查询 -->
      <el-form-item label="评论状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择评论状态" clearable>
          <el-option
              v-for="dict in comment_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 日期范围查询 -->
      <el-form-item label="评论日期" prop="dateRange">
        <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            value-format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 320px"
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item class="query-actions">
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 评论列表 -->
    <div class="comment-list">
      <div v-for="comment in commentList" :key="comment.commentId" class="comment-item">
        <div class="comment-header">
          <div class="user-info">
            <el-avatar :src="comment.userAvatar" :size="40" />
            <span class="user-name">{{ comment.userNickname }}</span>
            <span class="comment-time">{{ parseTime(comment.createTime) }}</span>
          </div>
          <div class="comment-status">
            <el-tag :type="getStatusType(comment.status)">
              {{ getStatusLabel(comment.status) }}
            </el-tag>
          </div>
        </div>
        
        <div class="comment-content">
          <p>{{ comment.content }}</p>
          <div class="comment-actions">
            <el-button 
              link 
              type="primary" 
              @click="handleLike(comment)"
              :class="{ 'liked': comment.isLiked }"
            >
              <el-icon><Star /></el-icon>
              {{ comment.likeCount }}
            </el-button>
            <el-button link type="primary" @click="handleReply(comment)">
              <el-icon><ChatDotRound /></el-icon>
              回复
            </el-button>
            <el-button link type="danger" @click="handleReport(comment)">
              <el-icon><Warning /></el-icon>
              举报
            </el-button>
          </div>
        </div>

        <!-- 回复列表 -->
        <div v-if="comment.replies && comment.replies.length > 0" class="reply-list">
          <div v-for="reply in comment.replies" :key="reply.commentId" class="reply-item">
            <div class="reply-header">
              <div class="user-info">
                <el-avatar :src="reply.userAvatar" :size="32" />
                <span class="user-name">{{ reply.userNickname }}</span>
                <span class="reply-time">{{ parseTime(reply.createTime) }}</span>
              </div>
            </div>
            <div class="reply-content">
              <p>{{ reply.content }}</p>
              <div class="reply-actions">
                <el-button 
                  link 
                  type="primary" 
                  @click="handleLike(reply)"
                  :class="{ 'liked': reply.isLiked }"
                >
                  <el-icon><Star /></el-icon>
                  {{ reply.likeCount }}
                </el-button>
                <el-button link type="danger" @click="handleReport(reply)">
                  <el-icon><Warning /></el-icon>
                  举报
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 评论弹窗 -->
    <el-dialog :title="title" v-model="open" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="评论内容" prop="content">
          <el-input
              v-model="form.content"
              type="textarea"
              :rows="4"
              placeholder="请输入评论内容"
              :maxlength="500"
              show-word-limit
          />
        </el-form-item>
        <el-form-item v-if="form.parentId" label="回复对象">
          <div class="reply-target">
            <el-avatar :src="form.replyUserAvatar" :size="32" />
            <span class="reply-user-name">{{ form.replyUserNickname }}</span>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 举报弹窗 -->
    <el-dialog title="举报评论" v-model="reportOpen" width="500px">
      <el-form ref="reportFormRef" :model="reportForm" :rules="reportRules" label-width="80px">
        <el-form-item label="举报原因" prop="reason">
          <el-select v-model="reportForm.reason" placeholder="请选择举报原因">
            <el-option label="垃圾广告" value="spam" />
            <el-option label="违法违规" value="illegal" />
            <el-option label="人身攻击" value="personal" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="详细说明" prop="description">
          <el-input
              v-model="reportForm.description"
              type="textarea"
              :rows="3"
              placeholder="请详细描述举报原因"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reportOpen = false">取消</el-button>
          <el-button type="primary" @click="submitReport">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Star, ChatDotRound, Warning } from '@element-plus/icons-vue'
import { 
  listComment, 
  addComment, 
  likeComment, 
  unlikeComment, 
  reportComment 
} from '@/api/healthSys/comment'

const router = useRouter()
const { proxy } = getCurrentInstance()

// 响应式数据
const loading = ref(false)
const open = ref(false)
const reportOpen = ref(false)
const title = ref('')
const commentList = ref([])
const total = ref(0)

// 评论状态字典
const comment_status = [
  { value: '0', label: '待审核' },
  { value: '1', label: '已发布' },
  { value: '2', label: '已删除' },
  { value: '3', label: '已拒绝' }
]

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: null,
  dateRange: []
})

// 表单数据
const form = reactive({
  commentId: null,
  content: null,
  parentId: null,
  replyUserAvatar: null,
  replyUserNickname: null
})

// 举报表单
const reportForm = reactive({
  commentId: null,
  reason: null,
  description: null
})

// 验证规则
const rules = {
  content: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur' }
  ]
}

const reportRules = {
  reason: [{ required: true, message: '请选择举报原因', trigger: 'change' }],
  description: [{ required: true, message: '请输入详细说明', trigger: 'blur' }]
}

// 初始化数据
onMounted(() => {
  getList()
})

// 获取评论列表
const getList = async () => {
  try {
    loading.value = true
    const params = {
      ...queryParams,
      beginDate: queryParams.dateRange?.[0],
      endDate: queryParams.dateRange?.[1]
    }

    const res = await listComment(params)
    commentList.value = res.rows
    total.value = res.total
  } catch (error) {
    proxy.$modal.msgError('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 查询处理
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  proxy.resetForm('queryRef')
  queryParams.dateRange = []
  queryParams.status = null
  handleQuery()
}

// 新增评论
const handleAdd = () => {
  resetForm()
  open.value = true
  title.value = '发表评论'
}

// 回复评论
const handleReply = (comment) => {
  resetForm()
  form.parentId = comment.commentId
  form.replyUserAvatar = comment.userAvatar
  form.replyUserNickname = comment.userNickname
  open.value = true
  title.value = '回复评论'
}

// 点赞评论
const handleLike = async (comment) => {
  try {
    if (comment.isLiked) {
      await unlikeComment(comment.commentId)
      comment.likeCount--
      comment.isLiked = false
    } else {
      await likeComment(comment.commentId)
      comment.likeCount++
      comment.isLiked = true
    }
  } catch (error) {
    proxy.$modal.msgError('操作失败')
  }
}

// 举报评论
const handleReport = (comment) => {
  reportForm.commentId = comment.commentId
  reportOpen.value = true
}

// 提交举报
const submitReport = async () => {
  try {
    await proxy.$refs.reportFormRef.validate()
    await reportComment(reportForm)
    proxy.$modal.msgSuccess('举报成功')
    reportOpen.value = false
  } catch (error) {
    console.error('举报失败:', error)
  }
}

// 提交评论
const submitForm = async () => {
  try {
    await proxy.$refs.formRef.validate()
    await addComment(form)
    proxy.$modal.msgSuccess('评论成功')
    open.value = false
    getList()
  } catch (error) {
    console.error('评论失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  form.commentId = null
  form.content = null
  form.parentId = null
  form.replyUserAvatar = null
  form.replyUserNickname = null
}

// 取消操作
const cancel = () => {
  open.value = false
  resetForm()
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    '0': 'warning',
    '1': 'success',
    '2': 'info',
    '3': 'danger'
  }
  return types[status] || 'info'
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    '0': '待审核',
    '1': '已发布',
    '2': '已删除',
    '3': '已拒绝'
  }
  return statusMap[status] || '未知'
}

const handleBack = () => {
  router.go(-1)
}
</script>

<style scoped>
.app-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.header-bar {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 32px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.header-bar:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
}

.back-btn {
  margin-right: 24px;
  padding: 12px 20px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.back-btn:hover {
  transform: translateX(-3px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 0.5px;
  background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.el-form {
  margin: 24px 0;
  padding: 32px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.el-form:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.08);
}

/* 评论列表样式 */
.comment-list {
  margin-top: 24px;
}

.comment-item {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.comment-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-name {
  font-weight: 500;
  color: #2c3e50;
}

.comment-time {
  color: #909399;
  font-size: 13px;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 16px;
}

.comment-actions {
  display: flex;
  gap: 16px;
  margin-top: 12px;
}

.comment-actions .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.comment-actions .el-button:hover {
  background-color: #f5f7fa;
}

.comment-actions .el-button.liked {
  color: #e74c3c;
}

/* 回复列表样式 */
.reply-list {
  margin-left: 52px;
  margin-top: 16px;
  padding-left: 16px;
  border-left: 2px solid #ebeef5;
}

.reply-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.reply-content {
  color: #606266;
  line-height: 1.5;
}

.reply-actions {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

/* 回复目标样式 */
.reply-target {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.reply-user-name {
  color: #606266;
  font-weight: 500;
}

/* 弹窗样式 */
.el-dialog {
  border-radius: 16px;
  overflow: hidden;
}

.el-dialog__header {
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__body {
  padding: 24px;
}

.el-dialog__footer {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .header-bar {
    padding: 16px;
  }

  .el-form {
    padding: 20px;
  }

  .el-date-picker {
    width: 100% !important;
  }

  .el-form-item__content {
    flex-wrap: wrap;
  }

  .el-button {
    margin-top: 8px;
    width: 100%;
  }

  .reply-list {
    margin-left: 24px;
  }
}
</style> 